#coding:utf-8
from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

import MySQLdb

from aliexpress.models import *
import json

from django.contrib.auth.models import Group
from django.contrib.auth.hashers import make_password
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings

import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )


host = settings.DATABASES['erp']['HOST']
user = settings.DATABASES['erp']['USER']
passwd = settings.DATABASES['erp']['PASSWORD']
db = settings.DATABASES['erp']['NAME']
port = int(settings.DATABASES['erp']['PORT'])


def linkDB():
    conn=MySQLdb.connect(host=host,user=user,passwd=passwd,db=db,port=port,charset='utf8')
    #conn=MySQLdb.connect(host='120.76.134.53',user='remote_user',passwd='tradetrends',db='erp',port=3306,charset='utf8')
    return conn


def my_custom_sql(sql):
    conn=linkDB()
    #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
    cursor = conn.cursor()

    # 数据修改操作——提交要求
    #cursor.execute(sql)
    #transaction.commit_unless_managed()

    # 数据检索操作,不需要提交
    cursor.execute(sql)
    rawData = cursor.fetchall()
    col_names = [desc[0] for desc in cursor.description]

    result = []
    for row in rawData:
        objDict = {}
        # 把每一行的数据遍历出来放到Dict中
        for index, value in enumerate(row):
            objDict[col_names[index]] = str(value)

        result.append(objDict)

    return result


def index(request):

    return render(request, 'aside/system/index.html', locals())



def permission(request):
    if not request.user.is_authenticated():
        #return redirect('signin')
        return redirect('/ucenter/login/'+"?from="+request.get_full_path())

    user = request.user
    if user.groups.filter(name='超级管理').count() < 1 :
        msg = '您无权限操作［权限管理］，请联系管理组操作！'
        return render(request,'aside/error.html',locals())

    action = request.POST.get('action',None)

    if action:
        if action == '_addPermission':
            addPermissionName = request.POST.get('addPermissionName',None)
            addPermissionCode = request.POST.get('addPermissionCode',None)
            addPermissionContent = request.POST.get('addPermissionContent',None)
            addPermissionType = request.POST.get('addPermissionType',None)

            if addPermissionName and addPermissionCode:
                try:
                    if addPermissionType:
                        try:
                            pt = PermissionType.objects.get(pk=addPermissionType)
                            Permission.objects.create(name=addPermissionName.strip(),codename=addPermissionCode.strip(),description=addPermissionContent,permission_type=pt)
                        except:
                            Permission.objects.create(name=addPermissionName.strip(),codename=addPermissionCode.strip(),description=addPermissionContent)
                    else:
                        Permission.objects.create(name=addPermissionName.strip(),codename=addPermissionCode.strip(),description=addPermissionContent,permission_type=pt)
                except Exception as e:
                    msg = str(e)
                    return render(request,'aside/error.html',locals())
            else:
                msg = '权限名称和权限代码必须填写！'
                return render(request,'aside/error.html',locals())

        elif action == '_addPermissionGroup':
            addPermissionGroupName = request.POST.get('addPermissionGroupName',None)
            addPermissionGroupOrder = request.POST.get('addPermissionGroupOrder',None)

            if addPermissionGroupName and addPermissionGroupName != '':
                try:
                    order = int(addPermissionGroupOrder)
                except:
                    order = 99
                PermissionType.objects.create(name=addPermissionGroupName.strip(),order=order)
            else:
                msg = '权限分组名称必须填写！'
                return render(request,'aside/error.html',locals())

        elif action == '_edit':
            editPermissionID = request.POST.get('editPermissionID',None)
            editPermissionName = request.POST.get('editPermissionName',None)
            editPermissionCodeName = request.POST.get('editPermissionCodeName',None)
            editPermissionGroup = request.POST.get('editPermissionGroup',None)
            editPermissionContent = request.POST.get('editPermissionContent',None)

            if editPermissionID and editPermissionName and editPermissionCodeName:
                p = Permission.objects.get(pk=editPermissionID)
                p.name = editPermissionName.strip()
                p.codename = editPermissionCodeName.strip()
                p.description = editPermissionContent.strip()
                if editPermissionGroup:
                    g = PermissionType.objects.get(pk=editPermissionGroup)
                    p.permission_type = g

                p.save()
            else:
                msg = '权限名称和权限代码必须填写！'
                return render(request,'aside/error.html',locals())

        elif action == '_delete':
            deletePermissionID = request.POST.get('deletePermissionID',None)
            if deletePermissionID:
                Permission.objects.filter(id=deletePermissionID).delete()
            else:
                msg = '删除失败！'
                return render(request,'aside/error.html',locals())


    permissionData = Permission.objects.all()
    permissionGroup = PermissionType.objects.all()

    return render(request, 'aside/system/permission-list.html', locals())


def members(request):
    if not request.user.is_authenticated():
        #return redirect('signin')
        return redirect('/ucenter/login/'+"?from="+request.get_full_path())

    user = request.user
    if user.groups.filter(name='超级管理').count() < 1 :
        msg = '您无权限操作［店铺管理］，请联系管理组操作！'
        return render(request,'aside/error.html',locals())

    userlist = User.objects.exclude(is_superuser=True)

    total = userlist.count()

    ungroup = userlist.filter(groups=None)

    groups = Group.objects.all()

    idx = request.GET.get('idx',None)

    #idxlist = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    idxlist = []

    for u in userlist:
        idxlist.append(str(u.username)[0].lower())

    idxlist = list(set(idxlist))

    if idx:
        userlist = userlist.filter(username__startswith=idx.lower())



    perms = []

    permTypes = PermissionType.objects.all()

    for t in permTypes:
        pt = dict()
        pt["TypeName"] = t.name
        pt["TypeID"] = t.id
        pt["Permission"] = list()
        pm = Permission.objects.filter(permission_type=t)
        for p in pm:
            pt["Permission"].append({'ID':p.id,'Name':p.name,'checked':False})

        perms.append(pt)

    action = request.POST.get('action',None)

    if action:
        if action == '_addGroup':
            groupName = request.POST.get('addGroupName','')
            if groupName != '':
                Group.objects.create(name=groupName)
            else:
                msg = '添加用户组失败：分组名称必须填写，且必须小于40个字'
                return render(request,'aside/error.html',locals())
        elif action == '_addUser':
            addUserName = request.POST.get('addUserName',None)
            addUserFirstName = request.POST.get('addUserFirstName',None)
            addUserEmail = request.POST.get('addUserEmail',None)
            addUserPassword = request.POST.get('addUserPassword',None)
            addConfirmPassword = request.POST.get('addConfirmPassword',None)
            groupSelect = request.POST.get('groupSelect',None)

            if addUserName and addUserFirstName and addUserEmail and addUserPassword:
                lastname = addUserFirstName.decode('utf-8')[0:1].encode('utf-8')
                newuser = User.objects.create(username=addUserName.strip(),first_name=addUserFirstName.strip(),last_name=lastname,email=addUserEmail.strip(),password=make_password(addUserPassword.strip()))
                if groupSelect:
                    g = Group.objects.get(pk=groupSelect)
                    newuser.groups.add(g)
            else:
                msg = '添加用户失败：用户名、姓名、邮箱、密码必须填写'
                return render(request,'aside/error.html',locals())

        elif action == '_remove':
            removeGroupID = request.POST.get('removeGroupID',None)
            removeUserID = request.POST.get('removeUserID',None)
            if removeUserID and removeGroupID:
                u = User.objects.get(pk=removeUserID)
                g = Group.objects.get(pk=removeGroupID)
                u.groups.remove(g)
            else:
                msg = '移除分组失败！'
                return render(request,'aside/error.html',locals())
        elif action == '_editUser':
            editUserID = request.POST.get('editUserID',None)
            editUserFirstName = request.POST.get('editUserFirstName',None)
            editUserEmail = request.POST.get('editUserEmail',None)
            editGroupSelect = request.POST.get('editGroupSelect',None)
            if editUserID:
                u = User.objects.get(pk=editUserID)
                if editUserFirstName.strip():
                    u.first_name = editUserFirstName.strip()
                if editUserEmail.strip():
                    u.email = editUserEmail.strip()
                if editGroupSelect:
                    g = Group.objects.get(pk=editGroupSelect)
                    u.groups.add(g)

            else:
                msg = '修改用户信息失败！'
                return render(request,'aside/error.html',locals())

    return render(request, 'aside/system/members.html', locals())

@csrf_exempt
def savePermission(request):
    data = dict()
    if not request.user.is_authenticated():
        data["error"] = True
        data["msg"] = u'未授权！'.decode()

    else:
        gid = request.POST.get('gid',None)
        uid = request.POST.get('uid',None)
        perms = request.POST.get('perms',None)
        if perms:
            if gid:
                try:
                    g = Group.objects.get(pk=gid)
                    try:
                        gp = GroupPermission.objects.get(group=g)
                        gp.permission = perms.strip(',')
                        gp.save()
                    except:
                        GroupPermission.objects.create(group=g,permission=perms.strip(','))

                    data["error"] = False
                    data["msg"] = u'保存成功！'.decode()
                except:
                    data["error"] = True
                    data["msg"] = u'无效用户组！'.decode()
            elif uid:
                try:
                    u = User.objects.get(pk=uid)
                    try:
                        up = UserPermission.objects.get(user=u)
                        up.permission = perms.strip(',')
                        up.save()
                    except:
                        UserPermission.objects.create(user=u,permission=perms.strip(','))

                    data["error"] = False
                    data["msg"] = u'保存成功！'.decode()
                except:
                    data["error"] = True
                    data["msg"] = u'无效用户！'.decode()
            else:
                data["error"] = True
                data["msg"] = u'用户或用户组错误！'.decode()

    return HttpResponse(json.dumps(data),content_type='application/json; charset=utf-8')


def ajaxGetPermission(request):
    data = dict()
    gid = request.GET.get('gid',None)
    uid = request.GET.get('uid',None)

    allPerms = []
    permTypes = PermissionType.objects.all()

    if gid:
        try:
            group = Group.objects.get(pk=gid)
            try:

                gPerms = GroupPermission.objects.get(group=group)
                groupPermission = str(gPerms.permission).strip(',').split(',')
                data["error"] = False
                for t in permTypes:
                    pt = dict()
                    pt["TypeName"] = t.name
                    pt["TypeID"] = t.id
                    pt["Permission"] = list()
                    pm = Permission.objects.filter(permission_type=t)

                    for p in pm:
                        if str(p.id) in groupPermission:
                            checked = True
                        else:
                            checked = False
                        pt["Permission"].append({'ID':p.id,'Name':p.name,'checked':checked})

                    allPerms.append(pt)
                data["PermissionList"]=allPerms
            except:
                #data["msg"] = u'无配置权限'.decode()
                data["error"] = False
                for t in permTypes:
                    pt = dict()
                    pt["TypeName"] = t.name
                    pt["TypeID"] = t.id
                    pt["Permission"] = list()
                    pm = Permission.objects.filter(permission_type=t)

                    for p in pm:
                        pt["Permission"].append({'ID':p.id,'Name':p.name,'checked':False})

                    allPerms.append(pt)
                data["PermissionList"]=allPerms
        except:
            data["msg"] = u'非法用户组'.decode()
            data["error"] = True

    elif uid:
        try:
            user = User.objects.get(pk=uid)
            try:
                uPerms = UserPermission.objects.get(user=user)
                userPermission = str(uPerms.permission).strip(',').split(',')
                data["error"] = False
                for t in permTypes:
                    pt = dict()
                    pt["TypeName"] = t.name
                    pt["TypeID"] = t.id
                    pt["Permission"] = list()
                    pm = Permission.objects.filter(permission_type=t)

                    for p in pm:
                        if str(p.id) in userPermission:
                            checked = True
                        else:
                            checked = False
                        pt["Permission"].append({'ID':p.id,'Name':p.name,'checked':checked})

                    allPerms.append(pt)
                data["PermissionList"]=allPerms
            except:
                #data["msg"] = u'无配置权限'.decode()
                data["error"] = False
                for t in permTypes:
                    pt = dict()
                    pt["TypeName"] = t.name
                    pt["TypeID"] = t.id
                    pt["Permission"] = list()
                    pm = Permission.objects.filter(permission_type=t)

                    for p in pm:
                        pt["Permission"].append({'ID':p.id,'Name':p.name,'checked':False})

                    allPerms.append(pt)
                data["PermissionList"]=allPerms
        except:
            data["msg"] = u'非法用户'.decode()
            data["error"] = True

    else:
        data["msg"] = u'非法操作'.decode()
        data["error"] = True

    return HttpResponse(json.dumps(data,ensure_ascii=False),content_type='application/json; charset=utf-8')


def ajaxUserList(request):
    data = dict()
    gid = request.GET.get('gid',None)
    idx = request.GET.get('idx',None)

    userlist = User.objects.all()

    if gid:
        if gid =='0':
            pass
        elif gid == '-1':
            userlist = userlist.filter(groups__isnull=True)
        else:
            userlist = userlist.filter(groups__id=gid)

    if idx:
        userlist = userlist.filter(username__startswith=idx.lower())

    data["Users"] = []

    for u in userlist:
        data["Users"].append({"id":u.id,"username":u.username,"last_name":u.last_name,"first_name":u.first_name,"email":u.email})

    data["Total"] = userlist.count()

    return HttpResponse(json.dumps(data),content_type='application/json; charset=utf-8')


def getUserList(request):
    data = dict()

    group = request.GET.get('group',1)
    storeID = request.GET.get('storeID',None)

    vips = User.objects.exclude(groups=3)
    vips = vips.exclude(first_name='')

    data["Group"] = 'VIP'

    data["Users"] = []

    selectedUser = []
    if storeID:
        sql = 'SELECT `USER_ID` FROM `sys_store_user` WHERE `STORE_ID`=%s'%storeID
        uids  = my_custom_sql(sql)

        for u in uids:
            selectedUser.append(u["USER_ID"])

    for u in vips:
        if str(u.id) in selectedUser:
            selected = True
        else:
            selected = False
        data["Users"].append({"username":u.username,"first_name":u.first_name,"selected":selected})


    return HttpResponse(json.dumps(data),content_type='application/json; charset=utf-8')


def allStore(request):
    if not request.user.is_authenticated():
        #return redirect('signin')
        return redirect('/ucenter/login/'+"?from="+request.get_full_path())

    user = request.user
    if user.groups.filter(name='超级管理').count() < 1 :
        msg = '您无权限操作［店铺管理］，请联系管理组操作！'
        return render(request,'aside/error.html',locals())

    action = request.POST.get('action',None)

    vips = User.objects.exclude(groups=3)
    vips = vips.exclude(first_name='')


    if action:
        if action == '_editStore':
            editStoreID = request.POST.get('editStoreID',None)
            editStoreType = request.POST.get('editStoreType',None)
            editStoreHost = request.POST.get('editStoreHost',None)
            editStoreServiceIP = request.POST.get('editStoreServiceIP',None)
            editStoreClientID = request.POST.get('editStoreClientID',None)
            editStoreAppSecret = request.POST.get('editStoreAppSecret',None)
            editStoreRedirectURL = request.POST.get('editStoreRedirectURL',None)
            editStoreRefreshToken = request.POST.get('editStoreRefreshToken',None)
            editStoreAccessToken = request.POST.get('editStoreAccessToken',None)

            if editStoreID != '0':
                sql = 'UPDATE `sys_store` SET '
                sql += '`TYPE`= %s '%editStoreType
                sql += ', `HOST`= "%s" '%editStoreHost.strip()
                sql += ', `SERVICE_IP`= "%s" '%editStoreServiceIP.strip()
                sql += ', `CLIENT_ID`= "%s" '%editStoreClientID.strip()
                sql += ', `APPSECRET`= "%s" '%editStoreAppSecret.strip()
                sql += ', `REDIRECT_URL`= "%s" '%editStoreRedirectURL.strip()
                sql += ', `REFRESHTOKEN`= "%s" '%editStoreRefreshToken.strip()
                sql += ', `ACCESSTOKEN`= "%s" '%editStoreAccessToken.strip()

                sql += ',`MODIFY_USER_ID` = %s '%str(user.id)
                sql += ',MODIFY_USER_NAME = "%s" '%str(user.username)
                sql += ',`MODIFY_DATE` = NOW() '

                sql += 'WHERE `ID`= %s'%editStoreID

                #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
                conn=linkDB()
                cursor = conn.cursor()
                cursor.execute(sql)
                conn.commit()

            else:
                msg = '更新店铺失败！'
                return render(request,'aside/error.html',locals())


        elif action == '_delete':
            storeID = request.POST.get('deleteStoreID',None)

            if storeID != '0':
                sql = 'DELETE FROM `sys_store` WHERE `ID`=%s'%(storeID)
                #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
                conn=linkDB()
                cursor = conn.cursor()
                cursor.execute(sql)
                conn.commit()
            else:
                msg = '删除店铺失败！'
                return render(request,'aside/error.html',locals())

        if action == '_addUser':
            storeID = request.POST.get('addUserStoreID',None)
            userList = request.POST.getlist('userList',None)

            if storeID != '0' and len(userList)>0:
                #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
                conn=linkDB()
                cursor = conn.cursor()
                for u in userList:
                    usr = User.objects.get(username__exact=u)

                    sql = 'INSERT IGNORE INTO `sys_store_user` (`STORE_ID`,`USER_ID`,`CREATE_USER_ID`,`CREATE_USER_NAME`,`CREATE_DATE`) VALUES ( '
                    sql += '%s,%s,%s,"%s",NOW())'%(storeID,str(usr.id),str(user.id),user.username)
                    cursor.execute(sql)
                    conn.commit()
            else:
                msg = '用户授权失败！'
                return render(request,'aside/error.html',locals())

    allCompany = my_custom_sql('SELECT `ID`,`NAME` FROM `sys_company`')

    storeData = my_custom_sql('SELECT `sys_company`.`NAME`,`sys_store`.`COMPANY_ID`,`sys_store`.`ID`,`sys_store`.`TYPE`,`sys_store`.`HOST`,`sys_store`.`SERVICE_IP`,`sys_store`.`CLIENT_ID`,`sys_store`.`APPSECRET`,`sys_store`.`REDIRECT_URL`,`sys_store`.`REFRESHTOKEN`,`sys_store`.`ACCESSTOKEN`,`sys_store`.`CREATE_DATE` FROM `sys_store`,`sys_company` WHERE sys_store.COMPANY_ID=sys_company.ID')

    return render(request, 'aside/system/store-list-all.html', locals())

def storeList(request,id):
    if not request.user.is_authenticated():
        #return redirect('signin')
        return redirect('/ucenter/login/'+"?from="+request.get_full_path())

    user = request.user
    if user.groups.filter(name='超级管理').count() < 1 :
        msg = '您无权限操作［店铺管理］，请联系管理组操作！'
        return render(request,'aside/error.html',locals())

    action = request.POST.get('action',None)

    vips = User.objects.filter(groups=1)
    vips = vips.exclude(first_name='')


    if action:
        if action == '_editStore':
            editStoreID = request.POST.get('editStoreID',None)
            editStoreType = request.POST.get('editStoreType',None)
            editStoreHost = request.POST.get('editStoreHost',None)
            editStoreServiceIP = request.POST.get('editStoreServiceIP',None)
            editStoreClientID = request.POST.get('editStoreClientID',None)
            editStoreAppSecret = request.POST.get('editStoreAppSecret',None)
            editStoreRedirectURL = request.POST.get('editStoreRedirectURL',None)
            editStoreRefreshToken = request.POST.get('editStoreRefreshToken',None)
            editStoreAccessToken = request.POST.get('editStoreAccessToken',None)

            if editStoreID != '0':
                sql = 'UPDATE `sys_store` SET '
                sql += '`TYPE`= %s '%editStoreType
                sql += ', `HOST`= "%s" '%editStoreHost.strip()
                sql += ', `SERVICE_IP`= "%s" '%editStoreServiceIP.strip()
                sql += ', `CLIENT_ID`= "%s" '%editStoreClientID.strip()
                sql += ', `APPSECRET`= "%s" '%editStoreAppSecret.strip()
                sql += ', `REDIRECT_URL`= "%s" '%editStoreRedirectURL.strip()
                sql += ', `REFRESHTOKEN`= "%s" '%editStoreRefreshToken.strip()
                sql += ', `ACCESSTOKEN`= "%s" '%editStoreAccessToken.strip()

                sql += ',`MODIFY_USER_ID` = %s '%str(user.id)
                sql += ',MODIFY_USER_NAME = "%s" '%str(user.username)
                sql += ',`MODIFY_DATE` = NOW() '

                sql += 'WHERE `ID`= %s'%editStoreID

                #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
                conn=linkDB()
                cursor = conn.cursor()
                cursor.execute(sql)
                conn.commit()

            else:
                msg = '更新店铺失败！'
                return render(request,'aside/error.html',locals())


        elif action == '_delete':
            storeID = request.POST.get('deleteStoreID',None)

            if storeID != '0':
                sql = 'DELETE FROM `sys_store` WHERE `ID`=%s'%(storeID)
                #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
                conn=linkDB()
                cursor = conn.cursor()
                cursor.execute(sql)
                conn.commit()
            else:
                msg = '删除店铺失败！'
                return render(request,'aside/error.html',locals())

        if action == '_addUser':
            storeID = request.POST.get('addUserStoreID',None)
            userList = request.POST.getlist('userList',None)

            if storeID != '0' and len(userList)>0:
                #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
                conn=linkDB()
                cursor = conn.cursor()
                for u in userList:
                    usr = User.objects.get(username__exact=u)

                    sql = 'INSERT IGNORE INTO `sys_store_user` (`STORE_ID`,`USER_ID`,`CREATE_USER_ID`,`CREATE_USER_NAME`,`CREATE_DATE`) VALUES ( '
                    sql += '%s,%s,%s,"%s",NOW())'%(storeID,str(usr.id),str(user.id),user.username)
                    cursor.execute(sql)
                    conn.commit()
            else:
                msg = '用户授权失败！'
                return render(request,'aside/error.html',locals())



    #companyData = my_custom_sql('SELECT `ID`,`NAME`,`MANAGER`,`NOTE`,`CREATE_DATE` FROM `sys_company` WHERE `MANAGER`="%s"'%user.first_name)
    companyData = my_custom_sql('SELECT `ID`,`NAME`,`MANAGER`,`NOTE`,`CREATE_DATE` FROM `sys_company` WHERE `ID`=%s'%id)

    if len(companyData)>0:
        company = companyData[0]
        storeData = my_custom_sql('SELECT `ID`,`TYPE`,`HOST`,`SERVICE_IP`,`CLIENT_ID`,`APPSECRET`,`REDIRECT_URL`,`REFRESHTOKEN`,`ACCESSTOKEN`,`CREATE_DATE` FROM `sys_store` WHERE `COMPANY_ID`=%s'%id)

    else:
        msg = '公司ID有误！'
        return render(request,'aside/error.html',locals())

    allCompany = my_custom_sql('SELECT `ID`,`NAME` FROM `sys_company`')

    return render(request, 'aside/system/store-list.html', locals())


def company(request):
    if not request.user.is_authenticated():
        #return redirect('signin')
        return redirect('/ucenter/login/'+"?from="+request.get_full_path())

    user = request.user
    if user.groups.filter(name='超级管理').count() < 1 :
        msg = '您无权限操作［公司管理］，请联系管理组操作！'
        return render(request,'aside/error.html',locals())

    #查找合伙人组的用户，可以管理公司
    vips = User.objects.filter(groups=5)

    action = request.POST.get('action',None)


    if action:
        if action == '_add':
            addCompanyName = request.POST.get('addCompanyName',None)
            addManager = request.POST.get('addManager',None)
            addContent = request.POST.get('addContent',None)

            if addCompanyName and addManager:

                sql = 'INSERT INTO `sys_company` (`NAME`,`MANAGER`,`NOTE`,`CREATE_USER_ID`,`CREATE_USER_NAME`,`CREATE_DATE`) VALUES ( '
                sql += '"%s" '%addCompanyName.replace('"','\\"').strip()
                sql += ',"%s" '%addManager.replace('"','\\"').strip()
                sql += ',"%s" '%addContent.replace('"','\\"').strip()
                sql += ',%s '%str(user.id)
                sql += ',"%s" '%str(user.username)
                sql += ',NOW()) '

                #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
                conn=linkDB()
                cursor = conn.cursor()
                cursor.execute(sql)
                conn.commit()

            else:
                msg = '公司名称、负责人需填写完整'
                return render(request,'aside/error.html',locals())
        elif action == '_edit':
            editCompanyName = request.POST.get('editCompanyName',None)
            editManager = request.POST.get('editManager',None)
            editContent = request.POST.get('editContent',None)
            companyID = request.POST.get('companyID',None)


            if editCompanyName and editManager and companyID != '0':

                sql = 'UPDATE `sys_company` SET '
                sql += '`NAME` = "%s" '%editCompanyName.replace('"','\\"').strip()
                sql += ',`MANAGER` = "%s" '%editManager.replace('"','\\"').strip()
                sql += ',`NOTE` = "%s" '%editContent.replace('"','\\"').strip()
                sql += ',`MODIFY_USER_ID` = %s '%str(user.id)
                sql += ',MODIFY_USER_NAME = "%s" '%str(user.username)
                sql += ',`MODIFY_DATE` = NOW() '
                sql += ' WHERE `ID`= %s '%(companyID)

                #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
                conn=linkDB()
                cursor = conn.cursor()
                cursor.execute(sql)
                conn.commit()

            else:
                msg = '公司名称、负责人不能为空'
                return render(request,'aside/error.html',locals())
        elif action == '_delete':
            companyID = request.POST.get('deleteCompanyID',None)

            if companyID != '0':
                sql = 'DELETE FROM `sys_company` WHERE `ID`=%s'%(companyID)
                #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
                conn = linkDB()
                cursor = conn.cursor()
                cursor.execute(sql)
                conn.commit()
            else:
                msg = '删除失败！'
                return render(request,'aside/error.html',locals())
        elif action == '_addStore':
            companyID = request.POST.get('addStoreCompanyID',None)
            storeType = request.POST.get('storeType','1')
            storeHost = request.POST.get('storeHost',None)
            storeServiceIP = request.POST.get('storeServiceIP',None)
            storeClientID = request.POST.get('storeClientID',None)
            storeAppSecret = request.POST.get('storeAppSecret',None)
            storeRedirectURL = request.POST.get('storeRedirectURL',None)
            storeRefreshToken = request.POST.get('storeRefreshToken',None)
            storeAccessToken = request.POST.get('storeAccessToken',None)


            if companyID != '0':
                sql = 'INSERT INTO `sys_store` (`COMPANY_ID`,`TYPE`,`HOST`,`SERVICE_IP`,`CLIENT_ID`,`APPSECRET`,`REDIRECT_URL`,`REFRESHTOKEN`,`ACCESSTOKEN`,`CREATE_USER_NAME`,`CREATE_USER_ID`,`CREATE_DATE`) VALUES ( '
                sql += '%s '%companyID
                sql += ', %s '%storeType
                sql += ', "%s" '%storeHost.strip()
                sql += ', "%s" '%storeServiceIP.strip()
                sql += ', "%s" '%storeClientID.strip()
                sql += ', "%s" '%storeAppSecret.strip()
                sql += ', "%s" '%storeRedirectURL.strip()
                sql += ', "%s" '%storeRefreshToken.strip()
                sql += ', "%s" '%storeAccessToken.strip()
                sql += ', "%s" '%user.first_name
                sql += ', %s '%user.id
                sql += ', NOW()) '

                #conn=MySQLdb.connect(host='localhost',user='root',passwd='zyc880128',db='erp',port=3306,charset='utf8')
                conn=linkDB()
                cursor = conn.cursor()
                cursor.execute(sql)
                conn.commit()

                return redirect('system:storeList',int(companyID))

            else:
                msg = '店铺添加失败！'
                return render(request,'aside/error.html',locals())


    companyList = my_custom_sql('SELECT `ID`,`NAME`,`MANAGER`,`NOTE`,`CREATE_DATE` FROM `sys_company`')


    return render(request, 'aside/system/company-list.html', locals())